import React from 'react'
import { changeNav } from '../../../actions'
import { wxzhctGetList } from '../../../actions/smartDr.js'
import { connect } from 'react-redux'
import { Button, Flex, WhiteSpace, Icon, Accordion, Popup, Toast, Modal, List, Switch } from 'antd-mobile'
import hhistory from '../../../history'
import CSSModules from 'react-css-modules'
import styles from './batchConfig.less'
import { ajaxGet, ajaxPost } from 'wxAjaxUtil'

let productCode = "100009";
const alert = Modal.alert;
const Item = List.Item;
let selectData = {
	"searchParam": "",
	"subProductCode": "",
	"expirationTime": "",
	"page": 1,
	"limit": 10
};
let confItem = [];
let firstTime = true;
let isSelectedNum = 0;
let switchState = true;

let iconStoreCode = require('../../../components/assets/icon_storeCode.svg');
let itemSelected = require('../../../components/assets/icon_gg_duoxuan_2.svg');
let itemNotSelected = require('../../../components/assets/icon_gg_duoxuan_1.svg');

@CSSModules(styles, { allowMultiple: true })
class AoTenant extends React.Component {

	constructor(props) {
		super(props);
		this.toggleState = this.toggleState.bind(this);
		this.allSelected = this.allSelected.bind(this);
		this.toConfig = this.toConfig.bind(this);
	}

	state = {
		detail: [],
		isAllchecked: false
	}

	componentWillMount() {
		firstTime = true;
		switchState = true;
		selectData = {
			"searchParam": "",
			"subProductCode": "",
			"expirationTime": "",
			"page": 1,
			"limit": 10
		};
	}

	componentDidMount() {
		let ctrl = this;
		this.props.tochangeNav({
			title: "批量设置", rbtn: [
				<div className="allSelected" onClick={() => ctrl.allSelected()}>全选</div>
			]
		});
		//获取已开通列表
		this.props.wxzhctGetList(selectData);

	}

	//全选切换
	allSelected() {
		if (this.state.detail.length > 0) {
			if (this.state.isAllchecked) {
				for (var i = 0; i < this.state.detail.length; i++) {
					this.state.detail[i].isSelected = false;
				}
				this.setState({
					detail: this.state.detail,
					isAllchecked: false
				})
				isSelectedNum = 0;
			} else {
				for (var i = 0; i < this.state.detail.length; i++) {
					this.state.detail[i].isSelected = true;
				}
				this.setState({
					detail: this.state.detail,
					isAllchecked: true
				})
				isSelectedNum = this.state.detail.length;
			}
		}
	}

	//单个切换选中状态
	toggleState(index) {
		let isAllchecked = true;
		isSelectedNum = 0;
		this.state.detail[index].isSelected = !this.state.detail[index].isSelected;
		for (var i = 0; i < this.state.detail.length; i++) {
			if (!this.state.detail[i].isSelected) {
				isAllchecked = false;
			} else {
				isSelectedNum = Number(isSelectedNum) + 1;
			}
		}
		this.setState({
			detail: this.state.detail,
			isAllchecked: isAllchecked
		})
	}

	configModal(storeCode, url, title, flag) {
		var ctrl = this;
		alert(title, <SwitchConfig />, [
			{ text: '取消', onPress: () => console.log('cancel'), style: 'default' },
			{
				text: '确定', onPress: () => {
					let data = { 'storeInfo': storeCode };
					data[flag] = switchState ? 1 : 0;
					ajaxPost(url, data, 'wxApiPath').then((res) => {
						this.props.wxzhctGetList(selectData);  //刷新数据
						Toast.success('修改成功', 1);
						firstTime = true;
						isSelectedNum = 0;
					}, (res) => {
						Toast.fail('修改失败', 1);
					})
				}
			},
		])
	}

	//去配置
	toConfig() {
		//筛选出被选择的门店
		let isSelectedMdCode = [];
		let name = this.props.location.state.name;
		let code = this.props.location.state.code;  //子产品（点餐、外送）的code
		if (this.state.detail.length <= 0) {
			Toast.fail('请先选择要配置的门店！', 2);
		} else {
			for (var i = 0; i < this.state.detail.length; i++) {
				if (this.state.detail[i].isSelected) {
					isSelectedMdCode.push(this.state.detail[i].storeCode);
				}
			}
			switch (this.props.location.state.alias) {
				case 'renew': //续费
					hhistory.push({
						pathname: '/renew',
						state: { productCode: productCode, renewalProductCode: code, renewalStoreCode: isSelectedMdCode }
					});
					break;
				case 'order':
					hhistory.push({
						pathname: '/wxDcConfig',
						state: { storeCode: isSelectedMdCode }
					});
					break;
				case 'delivery':
					hhistory.push({
						pathname: '/wxWsConfig',
						state: { storeCode: isSelectedMdCode }
					});
					break;
				case 'reserve':
					hhistory.push({
						pathname: '/wxYdConfig',
						state: { storeCode: isSelectedMdCode }
					});
					break;
				case 'invoice':
					hhistory.push({
						pathname: '/wxDzfpConfig',
						state: { storeCode: isSelectedMdCode }
					});
					break;
				case 'queue':
					this.configModal(isSelectedMdCode, '/o2o/sly/conf/apply/zhct/queue', '排队设置', 'queueFlg');
					break;
				case 'onlinePay':
					this.configModal(isSelectedMdCode, '/o2o/sly/conf/apply/zhct/onlinePay', '桌边付设置', 'onlinePayFlg');
					break;
				case 'xfPay':
					this.configModal(isSelectedMdCode, '/o2o/sly/conf/apply/zhct/xfPay', '享付设置', 'xfPayFlg');
					break;
			}
		}
	}

	render() {
		const { listData } = this.props;
		const { alias, name } = this.props.location.state;
		let ctrl = this;

		selectData.subProductCode = alias;

		let detail = (listData && listData.detail) ? listData.detail : [];

		if (firstTime && (detail.length > 0)) {
			for (var i = 0; i < detail.length; i++) {
				detail[i].isSelected = false;
			}
			this.setState({
				detail: detail
			})
			firstTime = false;
		}

		return (
			<div styleName="bodyWrap">
				<div styleName="word">{name}门店共有<span styleName="red"> {this.state.detail.length} </span>家，已选择<span styleName="red"> {isSelectedNum} </span>家</div>
				<div>
					{this.state.detail.map((item, index) => {
						return (
							<div styleName="listWrap" key={index} onClick={() => this.toggleState(index)} >
								<img styleName="listImg" src={item.storeLogo} />
								<div styleName="mdInfo">
									<div>{item.storeName}</div>
									<div styleName="infoCode"><Icon className="iconStoreCode" type={iconStoreCode} size={"sm"} /><span styleName="storeCode">{item.storeCode}</span></div>
								</div>
								<div styleName="checkbox">
									<Icon type={item.isSelected ? itemSelected : itemNotSelected} size={"sm"} />
								</div>
							</div>
						)
					})}
				</div>
				<div styleName="footer" onClick={this.toConfig}><span>已选<span styleName="numRed"> {isSelectedNum} </span>家门店，去配置</span><Icon className="rightIcon" type="right" size={"sm"} /></div>
			</div>
		)
	}
}

@CSSModules(styles, { allowMultiple: true })
class SwitchConfig extends React.Component {
	constructor(props) {
		super(props);
	}
	state = {
		isChecked: switchState
	}
	render() {
		return (
			<List>
				<Item extra={<Switch className="mySwitch" checked={this.state.isChecked} onClick={(v) => { switchState = !this.state.isChecked; this.setState({ isChecked: switchState }); }} />}></Item>
			</List>
		)
	}
}

const mapStateToProps = (state) => ({
	listData: state.wxSmartdrs.wxzhctListData
})
const mapDispatchToProps = (dispatch) => ({
	tochangeNav: navogj => dispatch(changeNav(navogj)),
	wxzhctGetList: selectData => dispatch(wxzhctGetList(selectData))
})

export default connect(mapStateToProps, mapDispatchToProps)(AoTenant)